package com.yc.web.EchoServer;

import com.yc.commons.RedisHelper;
import com.yc.model.JsonModel;
import com.yc.web.servlets.BaseServlet;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author SLGRoutine
 * @date 2024/7/5
 */
@WebServlet("/admin/userservletinfo.action")
public class UserChatServlet extends BaseServlet {


    /**
     * 获取初始化请求参数，并传递给前端
     * @param req
     * @param resp
     * @throws IOException
     */
    public void getServerInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, String> serverInfo = new HashMap<>();
        String protocol = req.isSecure() ? "wss" : "ws";
        String host = req.getServerName();
        int port = req.getServerPort();
        String contextPath = req.getContextPath();

        serverInfo.put("protocol", protocol);
        serverInfo.put("host", host);
        serverInfo.put("port", String.valueOf(port));
        serverInfo.put("contextPath", contextPath);

        JsonModel jm = new JsonModel();
        jm.setCode(1);//成功
        jm.setObj(serverInfo);
        writeJson(jm,resp);
    }
    public void initChatContent(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        Jedis jedis=RedisHelper.getRedisInstance();
        int uid=1;
        JsonModel jm=new JsonModel();
        List<Map<String,Object>>list=new ArrayList<>();
        // 获取有序集合的全部成员
        Set<Tuple> sortedSetMembers = jedis.zrangeWithScores("content_"+uid , 0, -1);
        // 打印输出每个成员及其分数
        for (Tuple member : sortedSetMembers) {
            String memberValue = member.getElement(); // 内容
            String timeForDat = getDateFormat((long) member.getScore());
            Map<String, Object> map = new HashMap<>();
            map.put("time", timeForDat);
            map.put("content", memberValue);
            list.add(map);
        }
        jm.setObj(list);
        jm.setCode(1);
        super.writeJson(jm,resp);
    }

    public void setMassage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("我是用户，在发请求");
        int uid = 1;
        String content = request.getParameter("content");
        System.out.println(content);
        //redis
        Jedis jedis = RedisHelper.getRedisInstance();
        UserEchoServer adminEchoServer = new UserEchoServer();
        adminEchoServer.send(String.valueOf(uid));
        // 当前时间戳
        long currentTimestamp = System.currentTimeMillis() / 1000;
        // 添加新成员到有序集合  content_1   时间戳   用户姓名:内容
        jedis.zadd("content_" + uid, currentTimestamp, "a:" + content);
        List<Map<String, Object>> returnList = new ArrayList<>();
        // 获取有序集合的全部成员
        Set<Tuple> sortedSetMembers = jedis.zrangeWithScores("content_" + uid, 0, -1);
        // 打印输出每个成员及其分数
        for (Tuple member : sortedSetMembers) {
            String memberValue = member.getElement(); // 内容
            String timeForDat = getDateFormat((long) member.getScore());
            Map<String, Object> map = new HashMap<>();
            map.put("time", timeForDat);
            map.put("content", memberValue);
            returnList.add(map);
        }
        System.out.println(returnList);
        JsonModel jm=new JsonModel();
        jm.setCode(1);
        jm.setObj(returnList);
        super.writeJson(jm,response);
    }
        /**
         * 将时间撮转换为日期格式事件
         *
         * @param score
         * @return
         */
        public static String getDateFormat(Long score) {
            // 创建 Date 对象并设置时间戳（需要乘以1000转换为毫秒）
            Date date = new Date(score * 1000L);

            // 创建 SimpleDateFormat 对象，定义日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // 使用 SimpleDateFormat 格式化 Date 对象
            String formattedDate = sdf.format(date);
            return formattedDate;
        }
}
